<template>
  <div class="desk-setting" v-loading="pendding">
    <!-- 启用服务台开关 -->
    <div class="desk-setting-switch-item">
      <div>
        <h4>{{$t('event.setting.deskSetting.title1')}}</h4>
        <div>{{$t('event.setting.deskSetting.des1')}}</div>
      </div>
      <el-switch
        v-model="serviceConfig.serviceStationEnabled"
        @change="changeState($event, 'serviceStationEnabled')"
        :active-text="serviceConfig.serviceStationEnabled ? $t('common.base.enable') : $t('common.base.disable')"
      ></el-switch>
    </div>

    <!-- 允许退回事件开关 -->
    <div class="desk-setting-switch-item">
      <div>
        <h4>{{$t('event.setting.deskSetting.title2')}}</h4>
        <div>
          {{$t('event.setting.deskSetting.des2')}}
        </div>
      </div>
      <el-switch
        v-model="serviceConfig.eventRollBack"
        @change="changeState($event, 'eventRollBack')"
        :active-text="serviceConfig.eventRollBack ? $t('common.base.enable') : $t('common.base.disable')"
      ></el-switch>
    </div>

    <!-- 审批备注必填开关 -->
    <div class="desk-setting-switch-item">
      <div>
        <h4>{{$t('event.setting.deskSetting.title3')}}</h4>
        <div>{{$t('event.setting.deskSetting.des3')}}</div>
      </div>
      <el-switch
        v-model="serviceConfig.approveRemark"
        @change="changeState($event, 'approveRemark')"
        :active-text="serviceConfig.approveRemark ? $t('common.base.enable') : $t('common.base.disable')"
      ></el-switch>
    </div>

    <!-- 启用自动分配规则开关 -->
    <div class="desk-setting-switch-item">
      <div>
        <h4>{{$t('event.setting.deskSetting.title4')}}</h4>
        <div>{{$t('event.setting.deskSetting.des4')}}</div>
      </div>
      <el-switch
        v-model="serviceConfig.autoDispatchEnabled"
        @change="changeState($event, 'autoDispatchEnabled')"
        :active-text="serviceConfig.autoDispatchEnabled ? $t('common.base.enable') : $t('common.base.disable')"
      ></el-switch>
    </div>

    <!-- 服务台事件分配规则表格 -->
    <div v-if="serviceConfig.autoDispatchEnabled" class="desk-setting-table">
      <div class="desk-setting-table-header">
        <h4>{{$t('event.setting.deskSetting.title5')}}</h4>
        <el-button type="primary" @click="createRule" icon="el-icon-plus"
        >{{$t('common.base.create')}}</el-button
        >
      </div>

      <el-table
        :data="dispatchRuleList"
        stripe
        border
        :empty-text="$t('event.setting.deskSetting.des5')"
      >
        <el-table-column
          prop="level"
          width="100"
          :label="$t('common.form.type.level')"
          align="center"
        ></el-table-column>
        <el-table-column prop="name" :label="$t('common.base.rulerName')" align="center">
        </el-table-column>
        <el-table-column :label="$t('common.base.operation')" align="center" width="200">
          <template slot-scope="scope">
            <i class="el-icon-edit" @click="editRule(scope.row.id)"></i>
            <i class="el-icon-close" @click="deleteRule(scope.row)"></i>
            <i
              class="iconfont icon-long-arrow-up"
              @click="moveRule(scope.$index, 'top')"
            ></i>
            <i
              class="iconfont icon-long-arrow-down"
              @click="moveRule(scope.$index, 'down')"
            ></i>
          </template>
        </el-table-column>
        <el-table-column
          :label="`${$t('common.base.enable')}/${$t('common.base.disable')}`"
          align="center"
          width="100"
          :resizable="false"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.according === '默认规则'">{{$t('common.base.open')}}</span>
            <el-switch
              v-else
              @change="ruleswitchEnable($event, scope.row)"
              v-model="scope.row.enabled === 1"
            ></el-switch>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 服务台待分配订阅管理下拉框 -->
    <div class="desk-setting-select-item">
      <div class="desk-select-title">
        <h4>{{$t('event.setting.deskSetting.title6')}}</h4>
        <el-tooltip
          :content="$t('event.setting.deskSetting.des6')"
          placement="bottom"
          effect="light"
        >
          <i class="el-icon-warning"></i>
        </el-tooltip>
      </div>
      <div class="desk-allot-executor-header-row">
        <biz-form-remote-select
          class="user-type-select"
          ref="TeamUserBizFormRemoteSelect"
          v-model="selectUsers"
          :placeholder="$t('common.placeholder.select')"
          :remote-method="fetchUsers"
          multiple
        >
          <div class="allot-users-option" slot="option" slot-scope="{ option }">
            <contact-user-item
              :user="option"
              :show-user-state="true"
              :state-color="stateColor"
              :show-tag="true"
            />
          </div>
        </biz-form-remote-select>
        <el-button type="primary" @click="allotSave">{{$t('common.base.save')}}</el-button>
      </div>
    </div>

    <!-- 服务台事件备注模板维护模块-->
    <div class="desk-remark-template-item">
      <h4>{{$t('event.setting.deskSetting.title7')}}</h4>
      <div class="desk-setting-table">
        <!-- 启用服务台事件备注模板开关 -->
        <div class="desk-setting-switch-item">
          <div>
            <h4>{{$t('event.setting.deskSetting.title8')}}</h4>
            <div>
              {{$t('event.setting.deskSetting.des7')}}
            </div>
          </div>
          <el-switch
            v-model="messageConfig.eventRemark"
            @change="changeState($event, 'eventRemark')"
            :active-text="messageConfig.eventRemark ? $t('common.base.enable') : $t('common.base.disable')"
          ></el-switch>
        </div>

        <!-- 服务台事件备注模板表格 -->
        <template v-if="messageConfig.eventRemark">
          <div class="desk-setting-table-header">
            <h4>{{$t('event.setting.deskSetting.title9')}}</h4>
            <el-button type="primary" @click="createRemark" icon="el-icon-plus"
            >{{$t('common.base.create')}}</el-button
            >
          </div>

          <el-table
            :data="eventRemarkList"
            stripe
            border
            :empty-text="$t('event.setting.deskSetting.des8')"
          >
            <el-table-column
              prop="sequence"
              width="100"
              :label="$t('common.base.SN')"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="content"
              :label="$t('common.base.content')"
              align="center"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              :label="$t('common.base.operation')"
              align="center"
              width="200"
              :resizable="false"
            >
              <template slot-scope="scope">
                <i class="el-icon-edit" @click="editRemark(scope.row.id)"></i>
                <i
                  class="el-icon-close"
                  @click="deleteEventRemark(scope.row.id)"
                ></i>
                <i
                  class="iconfont icon-long-arrow-up"
                  @click="moveRemark(scope.$index, 'top')"
                ></i>
                <i
                  class="iconfont icon-long-arrow-down"
                  @click="moveRemark(scope.$index, 'down')"
                ></i>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
    </div>

    <!-- 服务台事件分配规则弹出框 -->
    <DispatchRuleDialog ref="DispatchRuleDialog" />

    <!-- 服务台事件备注弹出框 -->
    <EventRemarkDialog ref="EventRemarkDialog" />
  </div>
</template>

<script>
import DeskNavBar from '../components/deskNavBar';
import ContactUserItem from '@src/component/common/BaseContact/ContactUserItem.vue';
import DispatchRuleDialog from '../components/DispatchRuleDialog';
import EventRemarkDialog from '../components/EventRemarkDialog';
import * as SettingApi from '@src/api/SettingApi.ts';
import http from '@src/util/http';
import { mapState, mapActions } from 'vuex';
import _ from 'lodash';

export default {
  name: 'desk-setting',
  components: {
    DeskNavBar,
    ContactUserItem,
    DispatchRuleDialog,
    EventRemarkDialog,
  },
  data() {
    return {
      pendding: false,
      // setData: {
      //   serviceStationConfig: {
      //     serviceStationEnabled: true,
      //     eventRollBack: true,
      //     approveRemark: true,
      //     autoDispatchEnabled: true,
      //   },
      //   messageConfig: {
      //     eventRemark: true,
      //   },
      // },
      params: {
        keyword: '',
        pageNum: 1,
      },
      // todo 初始值怎么拿
      // dispatchRuleList: [
      //   {
      //     level: 1,
      //     ruleName: '微风规则',
      //     id: 23,
      //     enabled: 1,
      //     according: '',
      //   },
      //   {
      //     level: 2,
      //     ruleName: '花荣测试事件分配规则	',
      //     id: 24,
      //     enabled: 0,
      //     according: '',
      //   },
      //   {
      //     level: 3,
      //     ruleName: '思清测试	',
      //     id: 25,
      //     enabled: 1,
      //     according: '',
      //   },
      //   {
      //     level: 4,
      //     ruleName: '默认规则',
      //     id: 27,
      //     enabled: 1,
      //     according: '默认规则',
      //   },
      // ],
      // selectUsers: [],
      stateColor: {}, // 用户工作状态颜色
      // todo 初始值怎么拿
      // eventRemarkList: [],
    };
  },
  computed: {
    ...mapState('service', [
      'serviceConfig',
      'dispatchRuleList',
      'selectUsers',
      'eventRemarkList',
      'messageConfig',
    ]),
  },
  // inject: ["initData"],
  mounted() {
    this.initializeStateColor();
    // todo 初始值
    this.initData();
  },
  methods: {
    ...mapActions('service', [
      'getServiceStationConfig',
      'getEventDispatchRules',
      'getAllotSubList',
      'getMessageConfig',
      'getEventRemarkList',
      'saveEventRemarkState',
      'saveSwitchState',
      'saveRuleState',
    ]),
    // 获取初始化数据
    initData() {
      this.getServiceStationConfig();
      this.getEventDispatchRules();
      this.getAllotSubList();
      this.getMessageConfig();
      this.getEventRemarkList();
    },

    // 开关状态更变
    async changeState(state, key) {
      let params = { state, key };
      const isRemark = key === 'eventRemark';
      try {
        if (isRemark) {
          await this.saveEventRemarkState(params);
        } else {
          await this.saveSwitchState(params);
        }
        this.$message.success(state ? this.$t('common.base.enabled') : this.$t('common.base.disabled'));
      } catch (error) {
        this.showErrorTip(error.message || this.$t('common.base.tip.saveFail'));
        console.error('save setting config state error', error);
      }
    },

    // 新建服务台事件分配规则
    createRule() {
      this.$refs.DispatchRuleDialog.openDialog('create');
    },

    // 编辑服务台事件分配规则
    editRule(id) {
      this.$refs.DispatchRuleDialog.openDialog('edit', id);
    },

    // 删除服务台事件分配规则
    async deleteRule(row) {
      try {
        // TODO-bdz 中文判断
        if (row.according === '默认规则') {
          return this.$message({
            showClose: true,
            duration: 1500,
            message: this.$t('event.setting.deskSetting.tips1'),
            type: 'error',
          });
        }

        if (!(await this.$platform.confirm(this.$t('event.setting.deskSetting.tips2')))) return;

        const params = { id: row.id };
        const result = await SettingApi.deleteRlue(params);
        if (result.status === 0) {
          this.$message({
            showClose: true,
            duration: 1500,
            message: this.$t('common.base.tip.deleteSuccess'),
            type: 'success',
          });
          this.getEventDispatchRules();
        } else {
          this.$message({
            showClose: true,
            duration: 1500,
            message: result.message,
            type: 'error',
          });
        }
      } catch (error) {
        console.error('delete rule error', error);
      }
    },

    // 移动事件配规则table数据
    async moveRule(index, direction) {
      try {
        if (index === 0 && direction === 'top') return;

        if (index === this.dispatchRuleList.length - 1 && direction === 'down')
          return;

        let arr = this.dispatchRuleList.map(item => {
          return {
            id: item.id,
          };
        });

        let moveItem = arr.splice(index, 1);
        if (direction === 'top') {
          arr.splice(index - 1, 0, moveItem[0]);
        } else {
          arr.splice(index + 1, 0, moveItem[0]);
        }
        arr.forEach((item, index) => {
          item.level = index + 1;
        });

        const result = await SettingApi.exchangeRule(arr);
        if (result.succ) {
          this.getEventDispatchRules();
        } else {
          this.$message({
            showClose: true,
            duration: 1500,
            message: result.message,
            type: 'error',
          });
        }
      } catch (error) {
        console.error('delete remark error', error);
      }
    },

    // 更改表格开关状态
    async ruleswitchEnable(enabled, row) {
      const params = {
        id: row.id,
        enabled: enabled ? 1 : 0,
      };
      try {
        this.saveRuleState(params);
        this.$message.success(enabled ? this.$t('common.base.enabled') : this.$t('common.base.disabled'));
      } catch (error) {
        this.showErrorTip(error.message || this.$t('common.base.tip.saveFail'));
      }
    },

    /**
     * 错误提示
     */
    showErrorTip(message) {
      this.$message({
        showClose: true,
        duration: 1500,
        type: 'error',
        message,
      });
    },

    // 查询用户列表
    fetchUsers(params) {
      let { keyword, pageNum } = params;
      this.params = {
        pageNum,
        keyword,
      };

      return SettingApi.getAllotUsersList(this.params).then(res => {
        if (!res || !res.list) return;

        res.list = res.list.map(item =>
          Object.freeze({
            label: item?.displayName || '',
            value: item?.userId || '',
            ...item,
          })
        );

        return res;
      });
    },

    async allotSave() {
      try {
        let ids = [];
        this.selectUsers.forEach(item => {
          ids.push(item.userId);
        });
        const params = {
          model: 'eventAllot',
          ids: ids.join(','),
        };
        const result = await SettingApi.saveAllotUsers(params);
        if (result.succ) {
          this.$message({
            showClose: true,
            duration: 1500,
            message: result.message,
            type: 'success',
          });
        }
        this.getAllotSubList();
      } catch (error) {
        console.error('save allot users error', error);
      }
    },

    /** 初始化工作状态的颜色 */
    initializeStateColor() {
      http
        .get('/setting/getStateColorMap')
        .then(
          res => (this.stateColor = _.assign({}, this.stateColor, res || {}))
        )
        .catch(err => console.error(err));
    },

    // 新建服务台事件备注模板
    createRemark() {
      // 首先判断是否已经存在了10条备注
      if (this.eventRemarkList.length >= 50) {
        return this.$message({
          showClose: true,
          duration: 1500,
          message: this.$t('event.setting.deskSetting.tips3'),
          type: 'warning',
        });
      }
      this.remarkRow = {};
      this.$refs.EventRemarkDialog.openDialog('create');
    },

    // 编辑服务台事件备注模板
    editRemark(id) {
      this.$refs.EventRemarkDialog.openDialog('edit', id);
    },

    // 删除服务台事件备注模板
    async deleteEventRemark(id) {
      try {
        if (!(await this.$platform.confirm(this.$t('event.setting.deskSetting.tips2')))) return;

        const params = { id };
        const result = await SettingApi.deleteEventRemark(params);
        if (result.succ) {
          this.$message({
            showClose: true,
            duration: 1500,
            message: result.message,
            type: 'success',
          });
          this.getEventRemarkList();
        } else {
          this.$message({
            showClose: true,
            duration: 1500,
            message: result.message,
            type: 'error',
          });
        }
      } catch (error) {
        console.error('delete remark error', error);
      }
    },

    // 移动事件备注table数据
    async moveRemark(index, direction) {
      try {
        if (index === 0 && direction === 'top') return;

        if (index === this.eventRemarkList.length - 1 && direction === 'down')
          return;

        const id1 = this.eventRemarkList[index].id;
        const id2 = direction === 'top'
          ? this.eventRemarkList[index - 1].id
          : this.eventRemarkList[index + 1].id;

        const params = {
          id1,
          id2,
        };
        const result = await SettingApi.exchangeRemark(params);
        if (result.succ) {
          this.getEventRemarkList();
        } else {
          this.$message({
            showClose: true,
            duration: 1500,
            message: result.message,
            type: 'error',
          });
        }
      } catch (error) {
        console.error('delete remark error', error);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.desk-setting {
  min-width: 730px;
  padding: 20px;
  width: 100%;
  background: #ffffff;
  border-radius: 4px;

  .desk-setting-switch-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  .desk-setting-table {
    padding-left: 20px;

    .desk-setting-table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
    }

    i {
      cursor: pointer;
      font-size: 13px;
      color: #909399;
    }
  }

  .desk-setting-select-item {
    margin: 20px 0 30px;

    .desk-select-title {
      display: flex;
      align-items: center;

      .el-tooltip {
        margin-left: 10px;
        cursor: pointer;
      }
    }

    .desk-allot-executor-header-row {
      display: flex;
      align-items: center;
      max-width: 80%;

      .el-button {
        margin-left: 10px;
      }

      .base-select-container .list-wrapper {
        height: 200px;
      }
    }
  }
}

h4 {
  margin: 10px 0px;
  font-size: 15px;
}

.user-type-select ::v-deep .list-wrapper {
  width: calc(80% - 287px);
  left: auto;
  // height: 300px;
  // overflow: hidden;
}
</style>
